/**
 * Created by huachuan on 2016/1/7.
 */
angular.module('shopdetailservice',[])
  //约局的Service
  .factory('Shop', function($resource,$rootScope,ENV){

    //访问的地址
    var APIUrl = ENV.api;
    var shopDetailJson,shopListJson,pageSize=10,
      saveGuideInfo;
    //获取$resource
    var getShopDetailResource = $resource(APIUrl+'findMeeting/getShopDetail.do');
    var getShopListByKeyResource = $resource(APIUrl+'releaseMeeting/getShopList.do');

    return{
        //保存店铺信息
        setGuideInfo:function(shopGuideInfo){
          saveGuideInfo = shopGuideInfo;
        },
        getGuideInfo:function(){
          return saveGuideInfo;
        },
        //获取店铺的详情
        getShopDetail:function(shopId){
          getShopDetailResource.save({
            shop_id:shopId
          },function(response){
            shopDetailJson = response;
            $rootScope.$broadcast('Shop.shopDetailUpdated');
          });
        },
      //根据关键字搜索约局地点
      getShopListByKey:function(searchKey,provinceId,cityId){
        var hasNextPage = true;
        getShopListByKeyResource.save({
          shop_name:searchKey,
          shop_province_id:provinceId,
          shop_city_id:cityId,
          pageIndex:1,
          pageSize:pageSize
        },function(response){
          if(response.shopList.length<pageSize){
            hasNextPage = false;
          }
            shopListJson = {
              hasNextPage:hasNextPage,
              nextPage:2,
              data:response.shopList
            }
          $rootScope.$broadcast('Shop.shopListUpdated');
        });
      },
      //获取更多的店铺店铺列表
      getMoreShopListByKey:function(searchKey,provinceId,cityId){
        if(shopListJson===undefined){
          return false;
        }
        var hasNextPage=shopListJson.hasNextPage;
        var nextPage=shopListJson.nextPage;
        var moreHomeData=shopListJson.data;
        if(!hasNextPage){
          return false;
        }
        getShopListByKeyResource.save({
          shop_name:searchKey,
          shop_province_id:provinceId,
          shop_city_id:cityId,
          pageIndex:nextPage,
          pageSize:pageSize
        },function(response){
          nextPage++;
          if(response.shopList.length<pageSize){
            hasNextPage = false;
          }
          moreHomeData = moreHomeData.concat(response.shopList);
          shopListJson = {
            hasNextPage:hasNextPage,
            nextPage: nextPage,
            data: moreHomeData
          };
          $rootScope.$broadcast('Shop.shopListUpdated');
        });
      },
      //是否有下一页
      hasNextPage: function() {
        if (shopListJson === undefined) {
          return false;
        }
        return shopListJson.hasNextPage;
      },
      getShopListJson:function(){
        return shopListJson.data;
      },
        //返回店铺详情的Json数据
        getShopDetailJson:function(){
          return shopDetailJson
        }
    }
  });
